package com.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wms.dao.WStockDao;
import com.wms.entity.WEntryStore;
import com.wms.entity.WOutStore;
import com.wms.dao.WOutStoreDao;
import com.wms.entity.WStock;
import com.wms.mytool.Result;
import com.wms.service.CommonService;
import com.wms.service.WOutStoreService;
import com.wms.vo.WOutStoreInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 出库单表(WOutStore)表服务实现类
 *
 * @author makejava
 * @since 2023-10-22 21:32:57
 */
@Service("wOutStoreService")
public class WOutStoreServiceImpl implements WOutStoreService {
    @Resource
    private WOutStoreDao wOutStoreDao;
    @Resource
    private WStockDao wStockDao;
    @Resource
    private CommonService commonService;

    @Override
    public Result selectAll() {
        List<WOutStoreInfo> outStoreInfos = this.wOutStoreDao.selectAll();
        if (outStoreInfos != null) {
            return new Result(200, outStoreInfos, "查询成功");
        } else {
            return new Result(400, null, "查询失败");
        }
    }

    @Override
    public Result addOutStore(List<WOutStore> wOutStore) {
        //查询所有出库单号
        int[] arr = this.wOutStoreDao.selectAllOutId();
        int max = 0;
        //出库单号存在
        if (arr.length>0) {
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] > max) {
                    max = arr[i];
                }
            }
        } else {
            //出库单号不存在，从10000开始
            max = 200000;
        }
        Date date = new Date();
        for (WOutStore outStore : wOutStore) {
            Result result=this.commonService.updateStock(outStore.getStoreId(), outStore.getPid(), outStore.getPNum(), false);
            if(result.getCode()==200){
                //出库单号递增
                outStore.setOutId(max + 1);
                outStore.setCreateTime(date);
                //新增出库信息
                this.wOutStoreDao.insert(outStore);
                //查询仓库是否有库存
                WStock wStock = this.wStockDao.selectByPidSid(outStore.getPid(), outStore.getStoreId());
                //有库存，库存量增加
                wStock.setNum(wStock.getNum() - outStore.getPNum());
                wStock.setMender(outStore.getCreator());
                wStock.setUpdateTime(date);
                this.wStockDao.updateById(wStock);
            }else{
                return result;
            }
        }
        return new Result(200, "", "出库成功");
    }

    @Override
    public Result deleteOutStore(Integer id) {
        QueryWrapper<WOutStore> qw = Wrappers.query();
        qw.eq("id", id);
        int i = this.wOutStoreDao.delete(qw);
        if (i == 1) {
            return new Result(200, i, "删除成功");
        } else {
            return new Result(400, null, "删除失败");
        }
    }
}
